package com.hwd.gmall.order.config;

import com.hwd.gmall.common.constant.Const;
import com.hwd.gmall.common.constant.OrderConst;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 订单微服务的延迟消息配置类
 *
 * @author 黄伟东/Victor
 * @date 2022/5/9 17:17
 */
@Configuration
public class OrderDelayRabbitConfig {

    /**
     * 创建订单数据同步的正常交换机
     *
     * @return org.springframework.amqp.core.Exchange
     */
    @Bean("orderNormalExchange")
    public Exchange orderNormalExchange() {
        return ExchangeBuilder.directExchange(OrderConst.ORDER_NORMAL_EXCHANGE).build();
    }

    /**
     * 创建订单数据同步的死信队列
     *
     * @return org.springframework.amqp.core.Queue
     */
    @Bean("orderDeadQueue")
    public Queue orderDeadQueue() {
        return QueueBuilder
                .durable(OrderConst.ORDER_DEAD_QUEUE)
                .withArgument(Const.X_DEAD_LETTER_EXCHANGE, OrderConst.ORDER_DEAD_EXCHANGE)
                .withArgument(Const.X_DEAD_LETTER_ROUTING_KEY, OrderConst.ORDER_DEAD_ROUTING_KEY)
                .withArgument(Const.X_MESSAGE_TTL, OrderConst.TTL)
                .build();
    }

    /**
     * 正常交换机和死信队列进行绑定
     *
     * @param orderNormalExchange 订单的正常交换机
     * @param orderDeadQueue      订单的死信队列
     * @return org.springframework.amqp.core.Binding
     */
    @Bean()
    public Binding deadBinding(@Qualifier("orderNormalExchange") Exchange orderNormalExchange,
                               @Qualifier("orderDeadQueue") Queue orderDeadQueue) {
        return BindingBuilder.bind(orderDeadQueue).to(orderNormalExchange).with(OrderConst.ORDER_NORMAL_ROUTING_KEY).noargs();
    }


    /**
     * 创建订单数据同步的死信交换机
     *
     * @return org.springframework.amqp.core.Exchange
     */
    @Bean("orderDeadExchange")
    public Exchange orderDeadExchange() {
        return ExchangeBuilder.directExchange(OrderConst.ORDER_DEAD_EXCHANGE).build();
    }

    /**
     * 创建订单数据同步的死信队列
     *
     * @return org.springframework.amqp.core.Queue
     */
    @Bean("orderNormalQueue")
    public Queue orderNormalQueue() {
        return QueueBuilder.durable(OrderConst.ORDER_NORMAL_QUEUE).build();
    }

    /**
     * 死信交换机和正常队列进行绑定
     *
     * @param orderDeadExchange 订单的死信交换机
     * @param orderNormalQueue  订单的正常队列
     * @return org.springframework.amqp.core.Binding
     */
    @Bean()
    public Binding normalBinding(@Qualifier("orderDeadExchange") Exchange orderDeadExchange,
                                 @Qualifier("orderNormalQueue") Queue orderNormalQueue) {
        return BindingBuilder.bind(orderNormalQueue).to(orderDeadExchange).with(OrderConst.ORDER_DEAD_ROUTING_KEY).noargs();
    }
}
